<template>
  <div ref="chartDom"></div>
</template>

<script>
import echarts from "echarts/lib/echarts"; //引入echarts核心源码
import "echarts/lib/chart/bar"; //引入柱状图
import "echarts/lib/component/title"; //引入柱状图标题title

import debounce from "lodash/debounce";

//监听echartresize
import { addListener, removeListener } from "resize-detector";
export default {
  props: {
    option: {
      type: Object,
      default: () => {},
    },
  },
  created() {
    this.resize = debounce(this.resize, 300);
  },
  mounted() {
    this.rendeChart();
    addListener(this.$refs.chartDom, this.resize);
  },
  watch: {
    //深度监听比较耗费性能 在父组件中做了处理  类似： option = {...option}
    // option: {
    //   handler(val) {
    //     console.log(val);
    //     this.chart.setOption(val);
    //   },
    //   deep: true,
    // },
    option(val) {
      this.chart.setOption(val);
    },
  },
  beforeDestroy() {
    //清除监听
    removeListener(this.$refs.chartDom, this.resize);
    //销毁chart实例 避免内存泄漏
    // if (this.charts.dispose) {
    // this.charts.dispose(); //清除 this.chart.resize();
    // }
    this.chart = null;
  },
  methods: {
    resize() {
      console.log("resize");
      this.chart.resize();
    },
    rendeChart() {
      // 基于准备好的dom，初始化echarts实例
      this.chart = echarts.init(this.$refs.chartDom);
      // 绘制图表
      this.chart.setOption(this.option);
    },
  },
};
</script>
